import React, { Component, PureComponent } from "react";

const Fnc = (props) => {
  console.log(111, props);
  return (
    <div>
      <h2>函数子组件</h2>
    </div>
  );
};

class App extends PureComponent {
  state = {
    // 值类型
    count: 0,
    // 引用类型
    obj: { a: 10 },
    list: [{ id: 0, name: "特朗普" }],
  };

  add = () => {
    this.setState({
      count: 2,
    });
  };

  /**
   *  决定组件是否重新渲染=>拦截器
   * @param {*} nextProps 最新的props的值
   * @param {*} nextState 最新的state的值
   */
  // shouldComponentUpdate(nextProps, nextState) {
  //   // console.log(nextProps, nextState);
  //   if (nextState.count !== this.state.count) {
  //     return true;
  //   }
  //   return false;
  // }
  cgobj = () => {
    const { obj, list } = this.state;
    // 引用地址一样，无法更新
    // obj.a = 100;
    // list.push({ id: 1, name: "普京" });
    // 创建一个新的数组或对象
    let newObj = { ...obj, a: 100 },
      newArr = [...list, { id: 1, name: "普京" }];
    this.setState({
      obj: newObj,
      list: newArr,
    });
  };

  render() {
    console.log("更新了");
    return (
      <div>
        <h1>性能优化</h1>
        <p>{this.state.count}</p>
        <p>{this.state.obj.a}</p>
        <ul>
          {this.state.list.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
        <button onClick={this.add}>值类型</button>
        <button onClick={this.cgobj}>引用类型</button>
        <hr />
        <Fnc key='1' />
      </div>
    );
  }
}

export default App;
